/*
 * Copyright (c) 2021. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.shide.businessuser.mvvm.view;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;

import com.lihang.ShadowLayout;
import com.shide.businessuser.GoodsAddActivity;
import com.shide.businessuser.R;
import com.shide.businessuser.ScanActivity;
import com.shide.businessuser.UI.PopWin_unAddGoods;
import com.shide.businessuser.UI.PopWin_unAuthentic;
import com.shide.businessuser.UI.PrograssDialogUitl;
import com.shide.businessuser.Utils.FuctionUtils;
import com.shide.businessuser.Utils.LogUtil;
import com.shide.businessuser.Utils.MessageEvent;
import com.shide.businessuser.Utils.SharePreferenceUtils;
import com.shide.businessuser.Utils.Utils;
import com.shide.businessuser.http.GlobleURL;
import com.shide.businessuser.http.OkhttpUtils;
import com.shide.businessuser.http.ParJson;
import com.shide.businessuser.http.adapter.GoodlistAdapter;
import com.shide.businessuser.http.entity.ErrorInfo;
import com.shide.businessuser.http.entity.Product;
import com.shide.businessuser.mvvm.adpter.GoodlistAdapter_mvvm;
import com.shide.businessuser.mvvm.model.Product_mvvm;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.Response;


/**
 * Created by Kevin on 2016/11/28.
 * Blog:http://blog.csdn.net/student9128
 * Description: HomeFragment
 */

public class HomeFragment_mvvm extends Fragment {

    private int auth_status; //认证状态
    //private int auth_status = 0; //认证状态
    private ImageView tvScanQr;
    private Button btnAddGoods;
    private Button btn_left_addGoods;
    private ListView listViewGoodslist;
    private ConstraintLayout containerUnAuthentic;
    private PrograssDialogUitl prograssDialogUitl;
    private String businessId;
    private List<Product_mvvm> goodsList;
    private ShadowLayout shadowLayout_container;
    private ShadowLayout sl_btn_left;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        auth_status = SharePreferenceUtils.getInt(getActivity(), GlobleURL.AUTHSTATUS, 0);
        businessId = SharePreferenceUtils.getString(getActivity(), GlobleURL.USER_ID);
        EventBus.getDefault().register(this);
    }


    /**
     * eventBus 传递消息 如果上架下架后进行重新刷新
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent messageEvent) {
       if (messageEvent.getCode() == MessageEvent.UP_DOWN_GOODS){
           prograssDialogUitl.showDialog();
           getGoodsListData();
       }


    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        prograssDialogUitl = new PrograssDialogUitl(getActivity());
       // auth_status = SharePreferenceUtils.getInt(getActivity(), GlobleURL.AUTHSTATUS, 0);
       // businessId = SharePreferenceUtils.getString(getActivity(), GlobleURL.USER_ID);
        initView(view);//认证过的listview先展示出来，gone掉其他布局

        if (listViewGoodslist.getVisibility() == View.VISIBLE
        || auth_status != 0) {
            //如果可见 == 认证过，则请求数据

            prograssDialogUitl.showDialog();

            getGoodsListData();//2，获取数据
        }



        return view;


    }

    private void getGoodsListData() {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(GlobleURL.Goodslist).newBuilder();
        urlBuilder.addQueryParameter("businessId",businessId);
        urlBuilder.addQueryParameter("limit","500000");
        urlBuilder.addQueryParameter("page","1");


        OkhttpUtils.get_addParam_token_Json(GlobleURL.Goodslist, urlBuilder, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        prograssDialogUitl.dismissDialog();

                        Toast.makeText(getActivity(), "请检查网络", Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                prograssDialogUitl.dismissDialog();
                String json = response.body().string();
                Boolean error = ParJson.isError(json);
               if (response.code() == 401){
                    FuctionUtils.BackLogin(response,getActivity());
                    return;
                }
                if (error) {
                    ErrorInfo errorData = ParJson.getErrorData(json);
                   // FuctionUtils.BackLogin(response, getActivity()); //401返回首页
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            LogUtil.e("homefrag",errorData.getMessage());
                           // Toast.makeText(getActivity(), errorData.getMessage(), Toast.LENGTH_SHORT).show();
                           // FuctionUtils.BackLogin(response,getActivity());
                        }
                    });
                } else {
                    List<Product_mvvm> goodsList = ParJson.getGoodsList_mvvm(json);
                    Message message = Message.obtain();
                    message.what = 0;
                    message.obj = goodsList;
                    handler.sendMessage(message);
                }
            }
        });

    }

    Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                goodsList = (List<Product_mvvm>) msg.obj;
                if (null != goodsList && goodsList.size() > 0) {
                    //左侧展示
                    shadowLayout_container.setVisibility(View.GONE);
                    containerUnAuthentic.setVisibility(View.GONE);
                    btn_left_addGoods.setVisibility(View.VISIBLE);
                    sl_btn_left.setVisibility(View.VISIBLE);
                    //进行适配
                    GoodlistAdapter_mvvm goodlistAdapter = new GoodlistAdapter_mvvm(goodsList,getActivity());
                    listViewGoodslist.setAdapter(goodlistAdapter);


                }
                if (null != goodsList && goodsList.size() == 0) {
                    shadowLayout_container.setVisibility(View.VISIBLE);
                    containerUnAuthentic.setVisibility(View.VISIBLE);
                    listViewGoodslist.setVisibility(View.GONE);
                    btn_left_addGoods.setVisibility(View.GONE);
                    sl_btn_left.setVisibility(View.GONE);
                    /*tvScanQr.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            PopWin_unAddGoods unAddGoods = new PopWin_unAddGoods(getActivity());
                            unAddGoods.showPopupWindow(tvScanQr);
                        }
                    });*/
                }




            }
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        //prograssDialogUitl.showDialog();
        //getGoodsListData();
        //listViewGoodslist.notifyAll();



        auth_status = SharePreferenceUtils.getInt(getActivity(),GlobleURL.AUTHSTATUS,0);
        SharePreferenceUtils.getString(getActivity(),GlobleURL.USERNAME);
        SharePreferenceUtils.getString(getActivity(),GlobleURL.PHONE);
        SharePreferenceUtils.getString(getActivity(),GlobleURL.IMGURL);
        SharePreferenceUtils.getString(getActivity(),GlobleURL.BUSINESSNAME);
        SharePreferenceUtils.getString(getActivity(),GlobleURL.ADDRESS);
        SharePreferenceUtils.getString(getActivity(),GlobleURL.COORDINATE);
    }



    private void initView(View view) {
        tvScanQr = (ImageView) view.findViewById(R.id.tv_scan_qr);
        btnAddGoods = (Button) view.findViewById(R.id.btn_add_goods);
        btn_left_addGoods = view.findViewById(R.id.btn_mainLfet_addGoods);
        containerUnAuthentic = (ConstraintLayout)view. findViewById(R.id.container_unAuthentic);


        listViewGoodslist = (ListView) view.findViewById(R.id.listView_goodslist);

        shadowLayout_container = view.findViewById(R.id.shadow2);
        sl_btn_left = view.findViewById(R.id.sl_btn_left);

        listViewGoodslist.setDivider(new ColorDrawable(Color.WHITE));
        listViewGoodslist.setDividerHeight(0);

        if (auth_status != 0) {
            /*tvScanQr.setTextColor(getActivity().getResources().getColor(R.color.scan_authened));
            tvScanQr.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.ic_scan_authened),
                    null,null,null);
            tvScanQr.setBackground(getActivity().getDrawable(R.drawable.ic_scan_exchage_));*/

            containerUnAuthentic.setVisibility(View.GONE);
            shadowLayout_container.setVisibility(View.GONE);
            listViewGoodslist.setVisibility(View.VISIBLE);//1.这里先展示出来
            btn_left_addGoods.setVisibility(View.VISIBLE);
            sl_btn_left.setVisibility(View.VISIBLE);
        }

        tvScanQr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (auth_status == 0) {
                    PopWin_unAuthentic popWin_unAuthentic = new PopWin_unAuthentic(getActivity());
                    popWin_unAuthentic.showPopupWindow(tvScanQr);

                } else {

                    if (Utils.isFastDoubleClick()) { return;}


                    if (goodsList != null && goodsList.size() > 0) {
                        new Handler().postDelayed(new Runnable() {

                            @Override
                            public void run() { //登录500毫秒，硬件等待时间，防止崩
                                Intent intent = new Intent(getActivity(), ScanActivity.class);
                                //Intent intent = new Intent(getActivity(), ExchangeActivity.class);
                                startActivity(intent);
                            }
                        },500);
                    }

                    if (goodsList != null && goodsList.size() == 0){
                        PopWin_unAddGoods unAddGoods = new PopWin_unAddGoods(getActivity());
                        unAddGoods.showPopupWindow(tvScanQr);
                    }




                }
            }
        });

        btnAddGoods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //if (Utils.isFastDoubleClick()) {
               //     return;
               // }

                if (auth_status == 0) { //未认证
                    PopWin_unAuthentic popWin_unAuthentic = new PopWin_unAuthentic(getActivity());
                    popWin_unAuthentic.showPopupWindow(btnAddGoods);
                } else {
                    Intent intent = new Intent(getActivity(),GoodsAddActivity.class);
                    startActivity(intent);
                }




            }
        });

        btn_left_addGoods.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // if (Utils.isFastDoubleClick()) {
               //     return;
               // }

                Intent intent = new Intent(getActivity(), GoodsAddActivity.class);
                startActivity(intent);
            }
        });

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


}
